package juc.异步回调.future.FutureTask;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.*;

/**
 * 使用FutureTask + 线程池 提升开发效率
 */
public class FutureThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Instant start = Instant.now();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        //任务一，并提交到线程池
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task1 over";
        });
        threadPool.submit(futureTask1);

        //任务二，并提交到线程池
        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task2 over";
        });
        threadPool.submit(futureTask2);


        //3，阻塞获取结果
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());

        //结束计时
        Duration dur = Duration.between(start, Instant.now());
        System.out.println("【耗时】（ms）" + dur.toMillis());

        //显式 释放线程池
        threadPool.shutdown();
    }
}